import json
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework import status, filters
from .serializers import PageNumberPagination, MenuTreeModelSerializer, MenuModelSerializer, RoleModelSerializer
from apps.backend import models
from drf_template_admin.services.RedisService import redis_connection
from drf_template_admin.utils.util import Util
    
class MenusAllTreeView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.Menus.objects.filter(pid=0,is_active=1).all().order_by('-sort')
        data = MenuTreeModelSerializer(instance=queryset, many=True).data
        return Response({'status': status.HTTP_200_OK, "data": data, 'message': 'success'})   
    
class MenusTreeView(APIView):
    def get(self, request, *args, **kwargs):
        redisConnection = redis_connection('token')
        redis_token = json.loads(redisConnection.get_redis(request.auth))
        queryset = models.Roles.objects.filter(id=redis_token['role'],is_active=1).first()
        data = RoleModelSerializer(instance=queryset, many=False).data

        menus = []
        util = Util()
        for item in data['menus']:
            item['children'] = util.tree(data['menus'], item['id'])
            if not item['pid']:
                menus.append(item)
                
        return Response({'status': status.HTTP_200_OK, "data":menus, 'message': 'success'})

class MenusListView(GenericAPIView):
    queryset = models.Menus.objects.all().order_by("-id")
    serializer_class = MenuModelSerializer 
    pagination_class = PageNumberPagination
    filter_backends = [filters.SearchFilter, ]  
    search_fields = ["menu_name", "is_active",]

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            list = self.get_serializer(instance=page, many=True)
            result = self.get_paginated_response(list.data)
            return Response({'status': status.HTTP_200_OK, "data": result, 'message': 'success'})
        
        list = self.get_serializer(instance=queryset, many=True)


    def post(self, request, *args, **kwargs):
        ser = MenuModelSerializer(data=request.data) 
        if not ser.is_valid():
            raise ValidationError({'status': status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "60001", "errorMessage": ser.errors})
        
        ser.save()
        return Response({'status': status.HTTP_201_CREATED, 'data': [], "message": "success"})

class MenusDetailView(APIView):
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        try:
            queryset = models.Menus.objects.get(pk=pk)
        except models.Menus.DoesNotExist:
            raise ValidationError({"status":status.HTTP_400_BAD_REQUEST, "errorCode": "60002", 'errorMessage': '数据不存在'}) 
        
        ser = MenuModelSerializer(instance=queryset, data=request.data) 
        if not ser.is_valid():
            raise ValidationError({'status': status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "60001", "errorMessage": ser.errors})
        
        ser.save()
        return Response({'status': status.HTTP_200_OK, 'data': [], "message": "success"})
    
    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        
        try:
            queryset = models.Menus.objects.get(id=pk)
        except models.Menus.DoesNotExist:
            raise ValidationError({"status":status.HTTP_400_BAD_REQUEST, "errorCode": "60002", 'errorMessage': '数据不存在'})
        
        queryset.is_active = True if queryset.is_active==False else False 
        message = "删除成功" if queryset.is_active==False else "恢复成功"
        queryset.save()  

        return Response({'status': status.HTTP_200_OK, "data": [], 'message': message}) 
    

   